(defun python-random()
  (interactive)
  (insert "import random;
random.random();
random.choice([1, 2, 3, 4]);
")
  )

(defun python-math()
  (interactive)
  (insert "import math;

print(math.pi);
")
  )

(defun python-keytap()
  (interactive)
  (insert "#!/usr/bin/env python  
  
\"\"\" 
Play http://www.google.com/doodles/hurdles-2012 . 
Code based on https://gist.github.com/3287367 .  
\"\"\"  

import time  
from autopy import key  
  
  
def play():  
    print '# switch to the candies game in your browser (you have 3 seconds)'  
    time.sleep(3)  
    s = time.time()  
    n=0  
    while time.time() - s < 15:  
        n=n+1  
        ##for _ in range(14):  
        ##    key.tap(key.K_LEFT)  
        ##    key.tap(key.K_RIGHT)  
        key.tap(' ')  
        if n<4:  
            time.sleep(0.01*n+0.1)  
        else:  
            time.sleep(0.12)  
  
#############################################################################  
  
if __name__ == \"__main__\":  
    play()  ")
  )

(defun python-socket()
  (interactive)
  (insert "# Echo server program
import socket

HOST = ''                 # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
    data = conn.recv(1024)
    if not data: break
    conn.sendall(data)
conn.close()

# Echo client program
import socket

HOST = 'daring.cwi.nl'    # The remote host
PORT = 50007              # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)

")
  )

(defun python-def()
  (interactive)
  (insert "#!/usr/bin/python

def abc(x):
    count = 0
    print x
    while count<9:
        print\"abc \",count,count
        count=count+1


x = int(raw_input(\"Please enter an integer: \"))
abc(x)        
")
  )

(defun python-print()
  ""
  (interactive)
  (insert "print __file__,inspect.stack()[0][3],inspect.stack()[0][2]

print __file__,self.__class__.__name__,inspect.stack()[0][3],inspect.stack()[0][2]            
")
  )

(defun python-ftp-base()
  (interactive)
  (insert "#!/usr/bin/python

import os, sys
import socket

HOST = 'localhost'                 # Symbolic name meaning all available interfaces
PORT = 21              # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
conn.sendall('220 connect successfully\\r\\n')
while 1:
    data = conn.recv(1024)
    print data
    if not data: break
    conn.sendall('220 connect successfully\\r\\n')    
conn.close()        
")
  )

(defun python-ftpclient()
  (interactive)
  (insert "from ftplib import FTP_TLS
ftps = FTP_TLS('ftp.python.org')
ftps.login()           # login anonymously before securing control channel
ftps.prot_p()          # switch to secure data connection
ftps.retrlines('LIST') # list directory content securely
")
  )

(defun python-file()
  (interactive)
  (insert "#!/usr/bin/python

import os, sys

# Open a file
fd = os.open( \"foo.txt\", os.O_RDWR|os.O_CREAT )

# Write one string
os.write(fd, \"This is test\")

# Close opened file
os.close( fd )

print \"Closed the file successfully!!\"
")
  )

(defun python-file-to-string()
  ""
  (interactive)
  (insert "#!/usr/bin/python

with open('D:/workspace/1.txt', 'r') as content_file:
    content = content_file.read()

print(content)    
")
  )



(defun python-debugger()
  (interactive)
  (insert "import pdb
pdb.set_trace()
")
  )

(defun python-freopen()
  (interactive)
  (insert "out = sys.stdout
sys.stdout = open('output.txt', 'w')
// do some work
sys.stdout = out")
  )

(defun python-text()
  ""
  (interactive)
  (insert "#!/usr/bin/python

with open('D:/workspace/1.txt', 'r') as content_file:
    content = content_file.read()

print(content)    
")
  )


(defun python-dir()
  (interactive)
  (insert "         
    import urllib2  
    import urllib  
    import os  
    import shutil  
      
    homedir = os.getcwd()  
      
    def walk_dir(homedir,topdown=True):  
        for root, dirs, files in os.walk(homedir, topdown):  
            #for name in files:  
                #if name=='.svn':  
                    #print(os.path.join(name))  
                    #os.remove(os.path.join(name))  
      
            for name in dirs:  
                if name=='.svn':  
                    print('Delete '+os.path.join(root,name))  
                    shutil.rmtree(os.path.join(root,name),ignore_errors=False)  
      
    walk_dir(homedir)  ")
  )

(defun python-readlines()
  ""
  (interactive)
  (insert "lines = open(\"/workspace/data.txt\").readlines();
a,b = lines[0].split(' ',1)

for l in lines[0:]:
    a,b = l.split(' ', 1)
    print a
    print b
")
  )

(defun python-dir-currentDirectory()
  ""
  (interactive)
  (insert "import os
files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:
    print(f)
")
  )

(defun python-dir-copy()
  (interactive)
  (insert "
** Dir WorkItems
*** DONE 1. copy all file with extenstion (*.pdb)
**** DONE 1.1 copy all file with extenstion (*.dll)    

import urllib2  
import urllib  
import os  
import shutil
import pdb

homedir = 'D:\\\\Path\\\\To\\\\Dir'

def walk_dir(homedir,topdown=True):  
    for root, dirs, files in os.walk(homedir, topdown):  
        for name in files:
            if name.find(\"dll\") > -1 or name.find(\"pdb\") > - 1:
                print(os.path.join(root,name))
                shutil.copy2(os.path.join(root,name), 'D:/test/dllpdb')

walk_dir(homedir)  
")
  )

(defun python-dict()
  "python dictionary example"
  (interactive)
  (insert "name2codepoint = {
    'AElig':    0x00c6, # latin capital letter AE = latin capital ligature AE, U+00C6 ISOlat1
}

codepoint2name = {}
entitydefs = {}

for (name, codepoint) in name2codepoint.items():
    print(name)
    print (codepoint)
    codepoint2name[codepoint] = name
    entitydefs[name] = chr(codepoint)

del name, codepoint                        
")
  )

(defun python-class()
  ""
  (interactive)
  (insert "class Complex:
     def __init__(self, realpart, imagpart):
         self.r = realpart
         self.i = imagpart

x = Complex(1.2,1.3)
print(x.r, x.i)

")
  )

(defun python-freopen()
  ""
  (interactive)
  (insert "if os.getenv('USER') != 'watashi':
	  sys.stdin = open('whatasha.in', 'r')
	  sys.stdout = open('whatasha.out', 'w')")
  )


(defun python-algorithm-linkedList()
  ""
  (interactive)
  (insert "
class link:
     def __init__(self, intPart, nextPart):
         self.data = intPart
         self.next = nextPart

Head = link(0,None)

current = Head

i=0

while i<10:
    p = link(i,None)
    current.next = p
    current = p
    i+=1
    
c = Head    

while c.next != None:
    print(c.data)
    c = c.next
")
  )

(defun python-yield()
  ""
  (interactive)
  (insert "def my_range(start, end, step):
    while start <= end:
        yield start
        start += step

for x in my_range(1, 10, 0.5):
    print x")
  )

(defun python-time()
  ""
  (interactive)
  (insert "import time

#use time.time() on Linux

start = time.clock()
for x in range(10000000):
    pass
stop = time.clock()

print stop - start

start = time.clock()
for x in xrange(10000000):
    pass
stop = time.clock()

print stop - start")
  )


